import modelExtend from 'dva-model-extend';
import { message } from 'antd';
import pageModel from './common';
import { query, create, remove, detail } from '../services/appVersion';
import { isSuccess } from '../configs';

export default modelExtend(pageModel, {
  namespace: 'appVersion',
  state: {
    list: [],
    queryData: {
      size: 10,
      current: 1,
      query: {},
    },
    currentItem: {},
    selectedKeys: [],
    addVisible: false,
    delVisible: false,
  },
  subscriptions: {

  },
  effects: {
    * queryList({ payload }, { call, put, select }) {
      const queryData = yield select(({ appVersion }) => appVersion.queryData);
      payload = { ...queryData, ...payload };
      delete payload.total;
      const res = yield call(query, payload);
      if (isSuccess(res)) {
        const { records, current, size, total } = res.data;
        const startIndex = (current - 1) * size;
        records.forEach((r, i) => {
          r.index = startIndex + i + 1;
        });
        yield put({
          type: 'set',
          list: records,
          queryData: {
            size,
            current,
            total,
          }
        });
      }
    },
    * create({ payload }, { call, put }) {
      const res = yield call(create, payload);
      if (isSuccess(res)) {
        message.success('添加成功!');
        yield put({
          type: 'set',
          addVisible: false,
        });
        yield put({
          type: 'queryList',
          payload: {},
        });
      }
    },
    * remove({ payload }, { call, put }) {
      const res = yield call(remove, payload);
      if (isSuccess(res)) {
        message.success('删除成功!');
        yield put({
          type: 'set',
          delVisible: false,
          selectedKeys: [],
        });
        yield put({
          type: 'queryList',
          payload: {},
        });
      }
    },
    * detail({ payload }, { call, put }) {
      const res = yield call(detail, payload);
      if (isSuccess(res)) {
        yield put({
          type: 'set',
          currentItem: res.data,
        });
      }
    }
  },
  reducers: {
    set(state, { type, ...other }) {
      return { ...state, ...other };
    },
    updateState(state, { payload }) {
      return { ...state, ...payload };
    }
  },
});
